package io.jpress.commons.word;

import com.jfinal.kit.LogKit;
import io.jboot.utils.StrUtil;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.office.LocalOfficeManager;

public class LibreOfficeManager {

    private static final LibreOfficeManager me = new LibreOfficeManager();

    public static LibreOfficeManager me() {
        return me;
    }

    private OfficeManager officeManager;
    private boolean started = false;
    private String officeHome;


    public boolean initIfNecessary(String officeHome) {
        if(StrUtil.isBlank(officeHome)){
            return false;
        }

        if (isStarted() && officeHome.equals(this.officeHome)){
            return true;
        }

        if (isStarted() && !officeHome.equals(this.officeHome)){
            stop();
        }

        try {
            this.officeHome = officeHome;
            officeManager = LocalOfficeManager.builder()
                    .officeHome(officeHome)
                    .install()
                    .build();
        } catch (Exception e) {
            LogKit.error(e.toString(), e);
            return false;
        }

        try {
            officeManager.start();
            started = true;
        } catch (OfficeException e) {
            LogKit.error(e.toString(), e);
            return false;
        }

        return true;
    }



    public boolean isStarted() {
        return started;
    }


    public void stop() {
        if (isStarted()) {
            started = false;
        }

        if (officeManager != null) {
            try {
                officeManager.stop();
            } catch (OfficeException e) {
                e.printStackTrace();
            }
        }
    }


}
